

import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import styles from './styles';
import SettingItem from './components/SettingItem';

interface NotificationSettings {
  appNotification: boolean;
  systemNotification: boolean;
  smsNotification: boolean;
  pendingNotification: boolean;
  resultNotification: boolean;
  reminderNotification: boolean;
  overtimeNotification: boolean;
}

const NotificationSettingsScreen = () => {
  const router = useRouter();
  
  const [notificationSettings, setNotificationSettings] = useState<NotificationSettings>({
    appNotification: true,
    systemNotification: true,
    smsNotification: false,
    pendingNotification: true,
    resultNotification: true,
    reminderNotification: true,
    overtimeNotification: true,
  });

  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    loadNotificationSettings();
  }, []);

  const loadNotificationSettings = async () => {
    try {
      setIsLoading(true);
      const savedSettings = await AsyncStorage.getItem('@notification_settings');
      if (savedSettings) {
        const parsedSettings = JSON.parse(savedSettings);
        setNotificationSettings(parsedSettings);
      }
    } catch (error) {
      console.error('加载通知设置失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const saveNotificationSettings = async (newSettings: NotificationSettings) => {
    try {
      await AsyncStorage.setItem('@notification_settings', JSON.stringify(newSettings));
      showSaveSuccess();
    } catch (error) {
      console.error('保存通知设置失败:', error);
      Alert.alert('错误', '保存设置失败，请重试');
    }
  };

  const showSaveSuccess = () => {
    Alert.alert('成功', '设置已保存', [{ text: '确定' }]);
  };

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleToggleSetting = (settingKey: keyof NotificationSettings) => {
    const newSettings = {
      ...notificationSettings,
      [settingKey]: !notificationSettings[settingKey],
    };
    setNotificationSettings(newSettings);
    saveNotificationSettings(newSettings);
  };

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton} 
          onPress={handleBackPress}
          activeOpacity={0.7}
        >
          <FontAwesome6 name="arrow-left" size={18} color="#D1D5DB" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>通知设置</Text>
        <View style={styles.headerPlaceholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        <View style={styles.content}>
          {/* 通知方式设置 */}
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <FontAwesome6 name="bell" size={18} color="#6366F1" />
              <Text style={styles.sectionTitle}>通知方式</Text>
            </View>
            
            <View style={styles.settingsList}>
              <SettingItem
                icon="mobile-screen"
                iconColor="#6366F1"
                iconBackgroundColor="rgba(99, 102, 241, 0.2)"
                title="应用内消息通知"
                description="在应用内显示通知消息"
                isEnabled={notificationSettings.appNotification}
                onToggle={() => handleToggleSetting('appNotification')}
              />
              
              <SettingItem
                icon="bell"
                iconColor="#F59E0B"
                iconBackgroundColor="rgba(245, 158, 11, 0.2)"
                title="手机系统通知"
                description="通过系统通知栏推送"
                isEnabled={notificationSettings.systemNotification}
                onToggle={() => handleToggleSetting('systemNotification')}
              />
              
              <SettingItem
                icon="comment-sms"
                iconColor="#EF4444"
                iconBackgroundColor="rgba(239, 68, 68, 0.2)"
                title="短信通知"
                description="重要通知通过短信发送"
                isEnabled={notificationSettings.smsNotification}
                onToggle={() => handleToggleSetting('smsNotification')}
              />
            </View>
          </View>

          {/* 通知类型设置 */}
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <FontAwesome6 name="gear" size={18} color="#8B5CF6" />
              <Text style={styles.sectionTitle}>通知类型</Text>
            </View>
            
            <View style={styles.settingsList}>
              <SettingItem
                icon="clock"
                iconColor="#F59E0B"
                iconBackgroundColor="rgba(245, 158, 11, 0.2)"
                title="待办通知"
                description="有新的待处理审批时通知"
                isEnabled={notificationSettings.pendingNotification}
                onToggle={() => handleToggleSetting('pendingNotification')}
              />
              
              <SettingItem
                icon="circle-check"
                iconColor="#10B981"
                iconBackgroundColor="rgba(16, 185, 129, 0.2)"
                title="审批结果通知"
                description="审批通过或驳回时通知"
                isEnabled={notificationSettings.resultNotification}
                onToggle={() => handleToggleSetting('resultNotification')}
              />
              
              <SettingItem
                icon="triangle-exclamation"
                iconColor="#EF4444"
                iconBackgroundColor="rgba(239, 68, 68, 0.2)"
                title="催办通知"
                description="收到催办请求时通知"
                isEnabled={notificationSettings.reminderNotification}
                onToggle={() => handleToggleSetting('reminderNotification')}
              />
              
              <SettingItem
                icon="clock"
                iconColor="#06B6D4"
                iconBackgroundColor="rgba(6, 182, 212, 0.2)"
                title="超时提醒"
                description="审批即将超时或已超时"
                isEnabled={notificationSettings.overtimeNotification}
                onToggle={() => handleToggleSetting('overtimeNotification')}
              />
            </View>
          </View>

          {/* 提示信息 */}
          <View style={styles.tipContainer}>
            <View style={styles.tipContent}>
              <FontAwesome6 name="circle-info" size={16} color="#6366F1" style={styles.tipIcon} />
              <View style={styles.tipTextContainer}>
                <Text style={styles.tipTitle}>提示：</Text>
                <Text style={styles.tipText}>• 部分通知类型可能需要同时开启对应的通知方式</Text>
                <Text style={styles.tipText}>• 短信通知仅用于重要事项，避免频繁打扰</Text>
                <Text style={styles.tipText}>• 您可以随时在此页面调整通知设置</Text>
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default NotificationSettingsScreen;

